"""
Author: Jian SuiYue kaohx0214@yeah.net
Date: 2025-05-15 10:35:00
LastEditTime: 2025-05-15 17:09:14
FilePath: LibraryManagerStudio/web/routes/message_api.py
"""
from fastapi import APIRouter, Depends, HTTPException, status, Query
from fastapi.responses import JSONResponse

from .token_api import validate_jwt
from ..deps import get_db
from ...database import DBManager
from ...datamodel import Message, Session, MessageBase

router = APIRouter()


@router.get("/get")
async def get_message(
        login: str = Query(...),
        session_id: int = Query(..., ge=1),
        db: DBManager = Depends(get_db)
):
    """
    Get the session message list by session_id.

    GET /get?login={your_token}&session_id={your_session_id}
    Args:
        login: Token.id
        session_id: Session.id
        db: DBManager
    """
    # verify
    validate_jwt(login)
    # check session exist
    session_exist = db.get(Session, filters={"id": session_id})
    if not session_exist.status or not session_exist.data:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Session ID {session_id} Not found")
    # get message
    message = db.get(Message, filters={"session_id": session_id})
    # return
    return JSONResponse(
        status_code=status.HTTP_200_OK,
        content={"status": True, "data": message.data, "message": "Get message successful"}
    )


@router.post("/gets")
async def get_messages(
        login: str = Query(...),
        page: int = Query(..., ge=1),
        size: int = Query(..., ge=1, le=100),
        db: DBManager = Depends(get_db)
):
    """
    Get the message list
    
    POST /gets?login={your_token}&page={page}&size={size}
    Args:
        login: Token.id
        page: page
        size: size
        db: DBManager
    """
    # verify
    validate_jwt(login)
    # get message list
    result = db.get(Message, page_info={"page": page, "size": size})
    if not result.status or not result.data:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"Unexpected Error: {result.message}")
    # return
    return JSONResponse(
        status_code=status.HTTP_200_OK,
        content={"status": True, "data": result.data, "message": "Get messages successful"}
    )


@router.post("/new")
async def new_message(
        message_base: MessageBase,
        login: str = Query(...),
        db: DBManager = Depends(get_db)
):
    """
    Create a new message.

    POST /new?token={your_token}
    Args:
        token: Token.id
        message_base: MessageBase
        db: DBManager
    """
    # verify
    validate_jwt(login)
    # check session exist
    session_exist = db.get(Session, filters={"id": message_base.session_id})
    if not session_exist.status or not session_exist.data:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"Session ID {message_base.session_id} Not found")
    # update 
    result = db.upsert(message_base)
    if not result.status or not result.data:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"Unexpected error at creating message")
    # return
    return JSONResponse(
        status_code=status.HTTP_201_CREATED,
        content={"status": True, "data": result.data[0], "message": "Message created successfully"}
    )


@router.delete("/delete")
async def delete_message(
        login: str = Query(...),
        message_id: int = Query(..., ge=1),
        db: DBManager = Depends(get_db)
):
    """
    Delete the message by message_id.

    DELETE /delete?token={your_token}&message_id={your_message_id}
    Args:
        login: Token.id
        message_id: Message.id
        db: DBManager
    """
    # verify
    validate_jwt(login)
    # check message exist
    message = db.get(Message, filters={"id": message_id})
    if not message.status or not message.data:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Message ID {message_id} not found")
    # delete
    result = db.delete(Message, filters={"id": message_id})
    if not result.status or not result.data:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"Unexpected Error: {result.message}")
    # return
    return JSONResponse(
        status_code=status.HTTP_200_OK,
        content={"status": True, "message": "Message deleted successfully"}
    )
